package com.spa.infrastructure.service.wx.msg;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.spa.domain.entity.AuthUser;
import com.spa.domain.service.AuthUserService;
import com.spa.infrastructure.enums.dict.base.RequestSourceEnum;
import com.spa.infrastructure.enums.dict.base.SourceTypeEnum;
import com.spa.infrastructure.service.wx.Constant;
import com.spa.infrastructure.service.wx.WXJsSdkService;
import com.spa.infrastructure.service.wx.config.ChatConfig;
import com.spa.infrastructure.service.wx.msg.chat.ChatTemplate;
import com.spa.infrastructure.service.wx.msg.chat.ChatTemplateData;
import com.spa.infrastructure.service.wx.msg.chat.WxMpErrorMsgEnum;
import com.spa.infrastructure.service.wx.result.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 发送模板消息
 * 公众号通知和小程序通知
 */
@Component
@Slf4j
public class WxMessageService {

    @Autowired
    private WXJsSdkService wxJsSdkService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ChatConfig chatConfig;

    @Autowired
    private AuthUserService authUserService;

    @Async
    public void send(String source, Long userId, String templateId, Map<String, String> wxMsg) {
        if (ObjectUtil.isEmpty(userId)) return;
        if (ObjectUtil.isEmpty(templateId)) return;
        if (ObjectUtil.isEmpty(wxMsg)) return;
        if (ObjectUtil.isEmpty(source)) return;

        AuthUser authUser =  authUserService.info(userId, source,null);
        if (BeanUtil.isEmpty(authUser) || ObjectUtil.isEmpty(authUser.getOpenId())){
            log.error("openId is null source={}",source);
            return;
        }

        if (source.equals(SourceTypeEnum.WeChat.getCode())){
            chatSend(authUser.getUserSource() ,authUser.getOpenId(),templateId, wxMsg);
        }
    }

    /**
     * 公众号通知
     * @param openId
     * @param templateId
     * @param wxMsg
     */
    private void chatSend(String userSource,String openId, String templateId, Map<String, String> wxMsg) {
        Map<String, ChatTemplateData> data = new HashMap<>();
        wxMsg.forEach((key, value) -> {
            data.put(key, new ChatTemplateData(valueSubstring(key,value), "#FF00FF"));
        });
        if(userSource.equals(RequestSourceEnum.Member.getCode())){
            push(SourceTypeEnum.WeChat, new ChatTemplate(openId, templateId, chatConfig.getUrl(), data), Constant.TEMPLATE_MSG_SEND_URL);
        } else if (userSource.equals(RequestSourceEnum.Massagist.getCode())) {
            push(SourceTypeEnum.WeChat, new ChatTemplate(openId, templateId, chatConfig.getStoreUrl(), data), Constant.TEMPLATE_MSG_SEND_URL);
        }
    }

    private void push(SourceTypeEnum typeEnum, Object wxMsg, String url) {
        Map<String, String> params = new HashMap<>();
        params.put("TOKEN", wxJsSdkService.getAccessToken(typeEnum));
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMsg, String.class, params);
        ErrorResult result = JSONUtil.toBean(responseEntity.getBody(), ErrorResult.class);
        if (result.getErrcode() != 0) {
            if (typeEnum.equals(SourceTypeEnum.WeChat)) {
                log.error("\n【请求地址】: {}\n【请求参数】：{}\n【响应数据】：code={} msg={}", url, wxMsg, JSONUtil.toJsonStr(result), WxMpErrorMsgEnum.findMsgByCode(result.getErrcode()));
            }
        }
    }

    private static String valueSubstring(String key,String value){
        if (key.contains("thing") && value.length()>20){
            return StrUtil.sub(value, 0, 20);
        }
        return value;
    }
}
